package com.meixiang.activity.homes.shopping;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.model.HttpParams;
import com.lzy.okhttputils.request.BaseRequest;
import com.meixiang.R;
import com.meixiang.adapter.shopping.GoodsListAdapter;
import com.meixiang.entity.shopping.MallMainGoodsEntity;
import com.meixiang.entity.shopping.result.GoodsSearchResult;
import com.meixiang.global.Config;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.recyclerview.OnItemClick;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AnimUtil;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;

import org.json.JSONObject;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 店铺的商品列表页面
 *
 * @author LZRUI
 */
public class StoreGoodsListActivity extends BaseActivity implements OnItemClick, OnRefreshListener, OnLoadMoreListener {

    private static final String TAG = "StoreGoodsListActivity";
    public static final String STORE_ID = "storeId";
    public static final String STORE_NAME = "storeName";

    @Bind(R.id.iv_to_top)
    ImageView ivToTop; // 回到顶部
    @Bind(R.id.swipe_target)
    RecyclerView ryGoodsList; // 商品列表
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh; // 刷新组件

    private GoodsListAdapter goodsListAdapter;
    private boolean isLoadMore; // 是否是加载更多
    private List<MallMainGoodsEntity> goodsList;

    private int pageNo = 1;
    private String keyWord = null; // 关键字
    private String isNewMarket = null; // Y新上市;N不是新上市
    private String isDiscount = null; // Y有折扣;N没有折扣
    private String goodsTransfreeCharge = null; //1包邮;0不包邮
    private String goodsPriceLow = null; // 查询低价格
    private String goodsPriceHigh = null; // 查询高价格
    private String orderMethod = ""; // 升序ASC/降序DESC
    private String storeId = null; // 店铺id
    private String gcId = null; // 商品类别id
    private String storeName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_store_goods_list);
        ButterKnife.bind(this);
        if (getIntent() != null) {
            storeId = getIntent().getStringExtra(STORE_ID);
            storeName = getIntent().getStringExtra(STORE_NAME);
        }
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        HttpUtils.tagCancelRequest(TAG);
    }

    @Override
    protected void initTitle() {
        setTitle(storeName);
    }

    @Override
    protected void initView() {
        // 初始化列表
        initGoodsRecyclerView();
    }

    /**
     * 初始化商品列表
     */
    private void initGoodsRecyclerView() {
        goodsListAdapter = new GoodsListAdapter(this);
        goodsListAdapter.setOnItemClickListener(this);
        ryGoodsList.setLayoutManager(new GridLayoutManager(this, 2));
        ryGoodsList.setAdapter(goodsListAdapter);
        ivToTop.setVisibility(View.GONE);

        ryGoodsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
                int firstVisibleItem = layoutManager.findFirstCompletelyVisibleItemPosition();

                if (firstVisibleItem > 0) {
                    AnimUtil.viewAlphaIn(ivToTop);
                } else {
                    AnimUtil.viewAlphaOut(ivToTop);
                }
            }
        });

        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);

        //自动刷新
//        mRefresh.post(new Runnable() {
//            @Override
//            public void run() {
//                mRefresh.setRefreshing(true);
//            }
//        });

        //RecyclerView滑到底部自动加载更多
        ryGoodsList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mRefresh.setLoadingMore(true);
                    }
                }
            }
        });
    }

    @Override
    protected void setData() {
        refreshGoodsData(1, false);
    }

    @Override
    @OnClick(R.id.iv_to_top)
    public void onClick(View v) {
        if (Tool.isFastDoubleClick()) return;
        switch (v.getId()) {
            // 回到顶部
            case R.id.iv_to_top:
                ryGoodsList.smoothScrollToPosition(0);
                break;
        }
    }

    @Override
    public void onLoadMore() {
        // TODO 加载更多
        refreshGoodsData(++pageNo, true);
    }

    @Override
    public void onRefresh() {
        // TODO 刷新
        refreshGoodsData(1, false);
    }

    @Override
    public void onItemClick(View view, int position) {
        // TODO 商品item点击事件
        Intent intent = new Intent(this, GoodsDetailActivity.class);
        intent.putExtra(GoodsDetailActivity.GOODS_ID, goodsList.get(position).getGoodsId());
        startActivity(intent);
    }

    /**
     * 刷新商品数据
     */
    private void refreshGoodsData(int page, boolean loadMore) {
        pageNo = page;
        isLoadMore = loadMore;
        getGoodsData(false);
    }

    /**
     * 获取商品列表
     *
     * @param isBtnRefresh 是否是无数据时，点击按钮的刷新
     */
    private void getGoodsData(boolean isBtnRefresh) {
        HttpParams params = new HttpParams();
        params.put("pageSize", "20");
        params.put("pageNo", String.valueOf(pageNo));
        if (!isBtnRefresh) {
            params.put("keyword", keyWord);
            params.put("isNewMarket", isNewMarket);
            params.put("isDiscount", isDiscount);
            params.put("goodsTransfreeCharge", goodsTransfreeCharge);
            params.put("goodsPriceLow", goodsPriceLow);
            params.put("goodsPriceHigh", goodsPriceHigh);
            params.put("storeId", storeId);
            params.put("gcId", gcId);
            params.put("orderField", "goodsStorePrice");
            params.put("orderMethod", orderMethod);
        }

        Log.i("lzrtest", params.toString());
        HttpUtils.post(Config.GOODS_SEARCH, TAG, params, new HttpCallBack(StoreGoodsListActivity.this) {

            @Override
            public void onBefore(BaseRequest request) {
                if (!Tool.isNetworkAvailable(activity)) {
                    OkHttpUtils.getInstance().cancelTag(StoreGoodsListActivity.this);
                    if (status == null) return;
                    status.showNoNewWork(null);
                }
            }

            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                GoodsSearchResult goodsSearchResult = AbJsonUtil.fromJson(result.toString(), GoodsSearchResult.class);
                if (goodsSearchResult != null && goodsSearchResult.getGoodsList() != null) {
                    if (isLoadMore) {
                        // 加载更多
                        goodsList.addAll(goodsSearchResult.getGoodsList());
                    } else {
                        goodsList = goodsSearchResult.getGoodsList();
                    }
                    if (mRefresh == null) return;
                    if (goodsSearchResult.getGoodsList().size() < 20) {
                        mRefresh.setLoadMoreEnabled(false);
                    } else {
                        mRefresh.setLoadMoreEnabled(true);
                    }
                }
            }

            @Override
            public void onError(String code, String message) {

            }

            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
               if (mRefresh!=null){
                   if (mRefresh.isRefreshing()){
                       mRefresh.setRefreshing(false);
                   }else if (mRefresh.isLoadingMore()){
                       mRefresh.setLoadingMore(false);
                   }
               }

                if (status == null || goodsListAdapter == null) return;
                if (goodsList == null || goodsList.size() == 0) {
                    status.showNoData("没有找到可以购买的商品，请刷新试试", "立即刷新", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getGoodsData(true);
                        }
                    });
                } else {
                    status.removeView();
                    goodsListAdapter.refreshData(goodsList);
                }
            }
        });
    }
}
